package com.example.geoserverdemo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgis.LineString;
import org.postgis.MultiLineString;
import org.postgis.PGgeometry;
import org.postgis.Point;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(CLine.class)
public class LineHandler extends BaseTypeHandler<CLine> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, CLine cLine, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public CLine getNullableResult(ResultSet resultSet, String s) throws SQLException {
        List<double[]> coordinates = new ArrayList<>();

        PGgeometry pGgeometry = (PGgeometry) resultSet.getObject(s);
        MultiLineString multiLineString = (MultiLineString) pGgeometry.getGeometry();
        if(multiLineString.getLines().length == 0) return null;

        // 解析点
        LineString firstLine = multiLineString.getLine(0);
        for (Point point : firstLine.getPoints()){
            double[] coord = new double[]{point.x, point.y};
            coordinates.add(coord);
        }
        CLine cLine = new CLine();
        cLine.setCoordinates(coordinates);
        return cLine;
    }

    @Override
    public CLine getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public CLine getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
